//
//  HomeViewController.m
//  StormWatch
//
//  Created by 王岩 on 2024/8/30.
//

#import "HomeViewController.h"
#import "HomeViewItemCell.h"
#import "HomeViewTopCell.h"
#import "LocationManager.h"
#import "HomeDataListViewController.h"
#import "BaseInfoTable+CoreDataClass.h"
#import "SleepTable+CoreDataClass.h"
#import "FRIDefine.h"
@interface HomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, HomeTopCellDelegate, FRQBluetoothManagerDelegate>

@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSArray * dataArr;
@property (nonatomic, strong) UIImageView * avatar, * logoView;
@property (nonatomic, strong) UILabel * nameLab;
@property (nonatomic, strong) NSString * stepNum, *caloriesStr, *distanceStr;
@property (nonatomic, strong) CBPeripheral *  peripheral;
@property (nonatomic, assign) unsigned long   sleepTime, heartRate, bloodOxygen;
@property (nonatomic, assign) BOOL   firstConnect;

@end

@implementation HomeViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self initData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disConnectBle) name:FRINotificationAtDidDisconnectPeripheral object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initData) name:@"appDidBecomeActive" object:nil];

    
    [[FRQBluetoothManager shareManager] setFilterForDiscoverPeripherals:^BOOL(NSString * _Nonnull peripheralName, NSDictionary * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
       
        return peripheralName.length>0 ;
    } andFilterForConnectToPeripherals:^BOOL(NSString * _Nonnull peripheralName, NSDictionary * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
        return YES;
    }];
    
    _firstConnect = YES;
    
    [[FRQBluetoothManager shareManager] addBleDelegate:self];
    
    self.distanceStr = @"0.00";
    self.caloriesStr = @"0.00";
    self.stepNum = @"0";
    self.sleepTime = self.heartRate = self.bloodOxygen = 0;
    
    [self initUI];
    
    [self  initData];
    
    [self updateTheme];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheme) name:@"k_change_theme" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfo) name:@"k_change_userInfo" object:nil];

//    [self startScanBle];
    
    // Do any additional setup after loading the view.
}

- (void)updateUserInfo {
    NSString * name = [[NSUserDefaults standardUserDefaults] valueForKey:@"_userName"];
    if (name) {
        self.nameLab.text = name;
    }else {
        self.nameLab.text = @"Storm";
    }
    
    NSData *data = [[NSUserDefaults standardUserDefaults] valueForKey:@"userAvatar"];
    if (data) {
        self.avatar.image = [UIImage imageWithData:data];
    }else {
        NSString * sex = [[NSUserDefaults standardUserDefaults] valueForKey:@"_userSex"];
        if ([sex isEqualToString:@"Female"]) {
            self.avatar.image = S_imageNamed(@"avatar_female_white");
        }else {
            self.avatar.image = S_imageNamed(@"avatar_man_white");
        }
    }
}

- (void)startScanBle {
    
    NSArray * arr = [[FRQBluetoothManager shareManager] scanPhoneConnectPeripherals];
    DDLogDebug(@"获取已连接的设备 数量 %d",(int)[arr count]);
    BOOL ha = NO;
    for (CBPeripheral* peripheral in arr)
    {
        if ([peripheral.identifier.UUIDString isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"]]) {
            ha = YES;
//            peripheral.macAddress = [[NSUserDefaults standardUserDefaults] valueForKey:peripheral.identifier.UUIDString];
            self.peripheral = peripheral;
            [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
            NSLog(@"😄😄😄😄😄 第一处");
        }
    }
    if (!ha && arr.count > 0) {
        self.peripheral = arr.firstObject;
        [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
        ha = YES;
    }
    if (!ha) {
        [[FRQBluetoothManager shareManager] scanPeripherals];
    }

}

- (void)initData {
    
    if ([FRQBluetoothManager shareManager].ready) {
        [self readData];
    }else {
        DDLogDebug(@"首页读取数据库数据");
        ///  读取数据库数据
        NSManagedObjectContext * context = [[DBManager sharedManager] managedObjectContext];
        NSFetchRequest *  request = [[NSFetchRequest alloc] initWithEntityName:@"BaseInfoTable"];
        NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
        request.sortDescriptors = @[sort];
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"deviceUUID = %@", [FRQBluetoothManager shareManager].uuid];
        request.predicate = predicate;
        NSArray<BaseInfoTable *> * result = [context executeFetchRequest:request error:nil];
        if (result.count) {
            self.stepNum = result.firstObject.stepData;
            self.distanceStr = result.firstObject.distanceData;
            self.caloriesStr = result.firstObject.caloriesData;
            self.heartRate = result.firstObject.heartRateData.integerValue;
        }
        
        NSFetchRequest *  request2 = [[NSFetchRequest alloc] initWithEntityName:@"SleepTable"];
        NSSortDescriptor * sort2 = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
        request2.sortDescriptors = @[sort2];
        NSPredicate * predicate2 = [NSPredicate predicateWithFormat:@"deviceUUID = %@", [FRQBluetoothManager shareManager].uuid];
        request.predicate = predicate2;
        NSArray<SleepTable *> * result2 = [context executeFetchRequest:request2 error:nil];
        
        if (result2.count) {
            self.sleepTime = result2.firstObject.deepData + result2.firstObject.lightData;
        }
        
        [self.collectionView reloadData];
        
        [self startScanBle];
    }
}

- (void)disConnectBle {
    DDLogDebug(@"首页 收到通知 -- 设备断开");
    self.firstConnect = NO;
    [FRQBluetoothManager shareManager].ready = NO;
}


- (void)updateTime {
    [StormCommandTool.sharedInstance writeStormCommand:Command_Bind Value:@[@0,@0,@0,@0] reBack:^(NSString * _Nonnull backData) {
        if (!backData) {
            return;
        }
        if (backData && [backData hasSuffix:@"0101000100"]) {
            [FRQBluetoothManager shareManager].ready = YES;
            [[StormCommandTool sharedInstance] updateDateAndTimeCallBack:^(BOOL success) {
                if (success) {
                    [self readData];
                }
                [[LocationManager sharedInstance] startUpdateLocation];
            }];
           
        }else {
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:[FRQBluetoothManager shareManager].curPeripheral];
        }
    }];
    
}

- (void)readData {
    DDLogDebug(@"首页开始读取数据");
    [[StormCommandTool sharedInstance] readRealTimeData:^(BOOL success, unsigned long stepData, unsigned long caloriesData, unsigned long distanceData, unsigned long heartRateData, unsigned long electricData) {
        self.heartRate = heartRateData;
        self.stepNum = [NSString stringWithFormat:@"%lu",stepData];
        self.caloriesStr = [NSString stringWithFormat:@"%.2f",caloriesData / 1000.0];
        self.distanceStr = [NSString stringWithFormat:@"%.2f",distanceData / 1000.0];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self readSleepData];
        });
        
        
        NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
        NSString * intervalStr = [SWTool timeWithYearMonthDayCountDown:[NSString stringWithFormat:@"%f",interval] Format:@"yyyy-MM-dd"];
        ///  更新数据库
        NSManagedObjectContext * context = [[DBManager sharedManager] managedObjectContext];
        NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"BaseInfoTable"];
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"date = %@ && deviceUUID = %@",intervalStr,[FRQBluetoothManager shareManager].uuid];
        request.predicate = predicate;
        NSArray<BaseInfoTable *> *result = [context executeFetchRequest:request error:nil];
        if (result.count > 0) {
            result[0].stepData = self.stepNum;
            result[0].caloriesData = self.caloriesStr;
            result[0].distanceData = self.distanceStr;
            result[0].heartRateData = [NSString stringWithFormat:@"%lu",heartRateData];
        }else {
            BaseInfoTable * st = [NSEntityDescription insertNewObjectForEntityForName:@"BaseInfoTable" inManagedObjectContext:context];
            st.stepData = self.stepNum;
            st.caloriesData = self.caloriesStr;
            st.distanceData = self.distanceStr;
            st.heartRateData = [NSString stringWithFormat:@"%lu",heartRateData];
            st.date = intervalStr;
            st.deviceUUID = [FRQBluetoothManager shareManager].uuid;
        }
        [[DBManager sharedManager] saveContext];
        
    }];
}

- (void)readSleepData {
    DDLogDebug(@"首页开始读取睡眠数据");
    [[StormCommandTool sharedInstance] readSleepData:^(BOOL success, unsigned long deepSleepData, unsigned long lightSleepData, unsigned long dateData) {
        
        self.sleepTime = deepSleepData + lightSleepData;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self readBloodOxygenData];
        });
    }];
}

- (void)readBloodOxygenData {
    DDLogDebug(@"首页开始读取血氧数据");
    [[StormCommandTool sharedInstance] readBloodOxygenData:^(BOOL success, NSArray * _Nonnull allData) {
        NSString * itemStr = allData.firstObject;
        NSString * rateD = [itemStr substringFromIndex:8];
        self.bloodOxygen = strtoll([[NSString stringWithFormat:@"0x%@",rateD] UTF8String], 0, 16);
        [self.collectionView reloadData];
        DDLogDebug(@"首页更新UI");
    }];
}

- (void)initUI {
    [self.view addSubview:self.collectionView];
    
    _avatar = [SWInitializer jy_initImageViewWithImage:S_imageNamed(@"avatar_man_white") on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(10);kMakeTV(kStatusBarHeight + 2);
        kMakeWHV(40, 40);
    }];
    
    _nameLab = [SWInitializer jy_initLabelWithText:@"Storm" textColor:[ThemeManager sharedInstance].textColor font:S_font(18) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeL(self.avatar.mas_right).offset(10);
        kMakeCenterY(self.avatar.mas_centerY);
    }];
    
    _logoView = [SWInitializer jy_initImageViewWithImage:nil on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeRV(-10);
        kMakeTV(kStatusBarHeight + 2);
        kMakeHV(40);
    }];
    
}

- (void)updateTheme {
    self.view.backgroundColor = [ThemeManager sharedInstance].themeColor;
    self.nameLab.textColor = [ThemeManager sharedInstance].textColor;
    if (ThemeManager.sharedInstance.themeValue == Theme_Default) {
        self.logoView.image = S_imageNamed(@"home_logo");
    }else {
        self.logoView.image = [S_imageNamed(@"home_logo") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        self.logoView.tintColor = [UIColor whiteColor];
    }
    [self.collectionView reloadData];
}

//- (void)updateData {
//    [self readData];
//}

- (void)clickHotView {
    HomeDataListViewController *vc = [[HomeDataListViewController alloc] initWithNibName:@"HomeDataListViewController" bundle:nil];
    vc.hidesBottomBarWhenPushed =  YES;
    vc.recordType = RecordType_Heat;
    [self.navigationController pushViewController:vc
                                         animated:YES];
}

- (void)clickCircleView {
    HomeDataListViewController *vc = [[HomeDataListViewController alloc] initWithNibName:@"HomeDataListViewController" bundle:nil];
    vc.hidesBottomBarWhenPushed =  YES;
    vc.recordType = RecordType_Step;
    [self.navigationController pushViewController:vc
                                         animated:YES];
}

- (void)clickDistanceView {
    HomeDataListViewController *vc = [[HomeDataListViewController alloc] initWithNibName:@"HomeDataListViewController" bundle:nil];
    vc.hidesBottomBarWhenPushed =  YES;
    vc.recordType = RecordType_Distance;
    [self.navigationController pushViewController:vc
                                         animated:YES];
}
#pragma mark -- FRQBluetoothManagerDelegate
-(void)onBLEManagerDiscoverPeripheral:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral advertisement:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if (self.firstConnect && [peripheral.identifier.UUIDString isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"]]) {
        [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:peripheral];
        NSLog(@"😄😄😄😄😄 第2处");
        [[FRQBluetoothManager shareManager] cancelScan];
    }
}

-(void)onBLEManagerConnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{

    DDLogDebug(@"首页  成功连接设备");
    [FRQBluetoothManager shareManager].userDisconnect = NO;
//    if (!peripheral.ancsAuthorized) {
//        [[FRQBluetoothManager shareManager] sendCommandData:[@"54590100" mj_JSONData] completion:^(NSString * _Nonnull resultString) {
//            
//        }];
//    }
}

- (void)onBLEManagerReady:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    if (self.firstConnect) {
        self.firstConnect = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self updateTime];
        });
    }
}
-(void)onBLEManagerStateChange:(id<FRBleAbility>)ability{
    
    switch (ability.state) {
        case FRQManagerStateUnsupported:
        {
//            toastHud.label.text = @"请检查你蓝牙使用权限或检查设备问题";
            DDLogDebug(@"请检查你蓝牙使用权限或检查设备问题");
        }
            break;
        case FRQManagerStateUnauthorized:
        {
//            toastHud.label.text = @"蓝牙设备暂无法使用，请在设置中授权";
            DDLogDebug(@"蓝牙设备暂无法使用，请在设置中授权");
        }
            break;
        case FRQManagerStatePoweredOff:
        {
//            toastHud.label.text =@"蓝牙已关闭";
            
            [[FRQBluetoothManager shareManager] cancelScan];
            DDLogDebug(@"蓝牙已关闭，请打开蓝牙");
            toast(@"");
        }
            break;
        case FRQManagerStatePoweredOn:
        {
//            toastHud.label.text = @"蓝牙已打开";
            DDLogDebug(@"蓝牙已打开");
            //scan
            [self  startScanBle];
        }
            break;
        default:
            break;
    }
    
}

#pragma mark --  CollectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {return 2;}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return 4;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HomeViewTopCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeViewTopCell" forIndexPath:indexPath];
        
        cell.delegate = self;
        
        [cell updateTheme];
        [cell updateValueStep:self.stepNum Distance:self.distanceStr Hot:self.caloriesStr];
        
        return cell;
    }else {
        HomeViewItemCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeViewItemCell" forIndexPath:indexPath];
        cell.row = indexPath.row;
        [cell updateTheme];
        
        [cell drawCorner:1 << indexPath.row];
        
        [cell updateValue];
        if (indexPath.row == 0) {
            cell.valueLab.attributedText = [SWTool attS1:self.distanceStr s2:SWString(@"Km") f1:S_bfont(22) c1:[ThemeManager sharedInstance].textColor f2:U_sfont(14) c2:[ThemeManager sharedInstance].textColor];
        }else if (indexPath.row == 1) {
            NSString * data = [NSString stringWithFormat:@"%lu", self.sleepTime / 60];
            NSMutableAttributedString * string  = [SWTool attS1:data s2:SWString(@"H") f1:S_bfont(22) c1:[ThemeManager sharedInstance].textColor f2:U_sfont(14) c2:[ThemeManager sharedInstance].textColor];
            
            data = [NSString stringWithFormat:@"   %lu", self.sleepTime % 60];
            NSMutableAttributedString * string2  = [SWTool attS1:data s2:SWString(@"minute") f1:S_bfont(22) c1:[ThemeManager sharedInstance].textColor f2:U_sfont(14) c2:[ThemeManager sharedInstance].textColor];
            [string appendAttributedString:string2];
            cell.valueLab.attributedText = string;
            
        }else if (indexPath.row == 2) {
            NSString * data = [NSString stringWithFormat:@"%lu", self.heartRate];
            cell.valueLab.attributedText = [SWTool attS1:data s2:SWString(@"BPM") f1:S_bfont(22) c1:[ThemeManager sharedInstance].textColor f2:U_sfont(14) c2:[ThemeManager sharedInstance].textColor];
        }else if (indexPath.row == 3) {
            NSString * data = [NSString stringWithFormat:@"%lu", self.bloodOxygen];
            cell.valueLab.attributedText = [SWTool attS1:data s2:@"" f1:S_bfont(22) c1:[ThemeManager sharedInstance].textColor f2:U_sfont(14) c2:[ThemeManager sharedInstance].textColor];
        }
        return cell;
    }
   
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth - 20, kScreenWidth / 2 - 10);
    }
    return CGSizeMake((kScreenWidth - 20 - 15) / 2.0, (kScreenWidth - 20 - 15) / 2.0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            self.tabBarController.selectedIndex = 1;
        }else if (indexPath.row == 1) {
            HomeDataListViewController *vc = [[HomeDataListViewController alloc] initWithNibName:@"HomeDataListViewController" bundle:nil];
            vc.hidesBottomBarWhenPushed =  YES;
            vc.recordType = RecordType_Sleep;
            [self.navigationController pushViewController:vc
                                                 animated:YES];
        }else if (indexPath.row == 2) {
            HomeDataListViewController *vc = [[HomeDataListViewController alloc] initWithNibName:@"HomeDataListViewController" bundle:nil];
            vc.hidesBottomBarWhenPushed =  YES;
            vc.recordType = RecordType_HeartReat;
            [self.navigationController pushViewController:vc
                                                 animated:YES];
        }else if (indexPath.row == 3) {
            HomeDataListViewController *vc = [[HomeDataListViewController alloc] initWithNibName:@"HomeDataListViewController" bundle:nil];
            vc.hidesBottomBarWhenPushed =  YES;
            vc.recordType = RecordType_BloodOxygen;
            [self.navigationController pushViewController:vc
                                                 animated:YES];
        }
    }
    
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 15;
        layout.minimumInteritemSpacing = 15;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, kNavigationBarHeight, kScreenWidth - 20, kScreenHeight - kNavigationBarHeight - kTabBarHeight) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerNib:[UINib nibWithNibName:@"HomeViewItemCell" bundle:nil] forCellWithReuseIdentifier:@"HomeViewItemCell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"HomeViewTopCell" bundle:nil] forCellWithReuseIdentifier:@"HomeViewTopCell"];
    }
    return _collectionView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
